package com.example.xlzx.controller;


import com.example.xlzx.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Currency;
import java.util.UUID;
import java.util.logging.Logger;

@RestController
@Tag(name = "文件上传")
@CrossOrigin
@RequestMapping("/xlzx")
public class UploadController {

    @Value("${server.port}")
    private String port;
    @Value("${ipaddr.ip}")
    private String ip;
    @Operation(summary = "文件上传头像")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile image) throws IOException {

        //获取文件名
        String originalFilename = image.getOriginalFilename();

        //构造唯一文件名（不重复）--uuid(通用唯一识别码)
        int index = originalFilename.lastIndexOf('.');
        String extname = originalFilename.substring(index);
        String newFilename = UUID.randomUUID().toString() + extname;

        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String url = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\images\\";

        String replace = url.replace("\\", "\\\\");

        //将文件储存在服务器的磁盘目录中
        image.transferTo(new File(replace + newFilename));
        return Result.ok("http://"+ip+":"+port+"/image/" + newFilename);


    }

}
